/*
 * This file is part of ELCube.
 *
 * ELCube is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ELCube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ELCube.  If not, see <https://www.gnu.org/licenses/>.
 */
package cn.nkpro.elcube.security.validate2;

import cn.nkpro.elcube.security.UserAccountService;
import cn.nkpro.elcube.security.bo.UserDetails;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 2、使用token访问系统
 * Created by bean on 2019/12/30.
 */
@Component
@Slf4j
@Order(1000)
public class NkAccessTokenAuthenticationFilter extends GenericFilterBean implements AuthenticationFilterV2 {

    @Autowired
    private AuthenticationUtils authenticationUtils;
    @Autowired
    private UserAccountService userDetailsService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {

                // 请求地址
                String url = ((HttpServletRequest) request).getRequestURI();
                // 区分客户端
                String client    = authenticationUtils.obtainParam(request, "elcube-client");
                // 用户名
                String username  = authenticationUtils.obtainParam(request, "elcube-user");
                // 请求时间戳，验证签名有效期
                String timestamp = authenticationUtils.obtainParam(request, "elcube-timestamp");
                // 随机字符串，避免签名重复使用来进行攻击
                String nonce     = authenticationUtils.obtainParam(request, "elcube-nonce");
                // 签名，验证密码
                String signature = authenticationUtils.obtainParam(request, "elcube-signature");

                if (StringUtils.isNoneBlank(client, username, timestamp, signature)) {
                    // 1、校验时间戳
                    AuthenticationUtils.validateTimestamp(timestamp);
                    // 2、校验随机字符串
                    authenticationUtils.checkNonce(username,nonce);
                    // 3、校验错误登陆次数
                    authenticationUtils.validateErrorsLogin(username, false, null, null);

                    try {

                        NkToken token = authenticationUtils.getToken(client, username);
                        if(token==null){
                            throw new BadCredentialsException("token已失效");
                        }

                        // 验证签名
                        if(!AuthenticationUtils.validateSignature(
                                url,
                                request.getParameterMap(),
                                timestamp,
                                token.getToken(),
                                nonce,
                                signature)){
                            throw new BadCredentialsException("验证错误");
                        }

                        UserDetails details = userDetailsService.loadUserByUsernameFromCache(username);

                        AuthenticationUtils.simpleValidate(details);
                        authenticationUtils.clearErrorsLogin(username);
                        authenticationUtils.extendToken(client,username);

                        AbstractAuthenticationToken auth = new NkAccessTokenAuthenticationToken(
                                client,
                                username,
                                token,
                                details.getAuthorities());
                        auth.setDetails(details);

                        SecurityContextHolder.getContext().setAuthentication(auth);
                    }catch (AuthenticationException e){
                        authenticationUtils.commence((HttpServletResponse)response, e);
                        return;
                    }
                }
            }
        }

        filterChain.doFilter(request, response);
    }
}
